//==============================================================================
#include "ServerReceiver.h"

//==============================================================================
ServerReceiver::ServerReceiver(GameServer* server)
{
	setServer(server);
	setIsReceiving(true);
}
//------------------------------------------------------------------------------
ServerReceiver::~ServerReceiver(void)
{
}
//------------------------------------------------------------------------------
void ServerReceiver::setServer(GameServer* server)
{
	this->server = server;
}
//------------------------------------------------------------------------------
GameServer* ServerReceiver::getServer()
{
	return this->server;
}
//------------------------------------------------------------------------------
void ServerReceiver::setIsReceiving(bool flag)
{
	this->_isReceiving = flag;
}
//------------------------------------------------------------------------------
bool ServerReceiver::isReceiving()
{
	return this->_isReceiving;
}
//------------------------------------------------------------------------------
DWORD ServerReceiver::run(void)
{
	return startReceiving();
}
//------------------------------------------------------------------------------
int ServerReceiver::startReceiving(void)
{
	try
	{
		getServer()->getSocket()->doBind();
		getServer()->getSocket()->doListen();

		ClientSocket* clientSocket;
		while (isReceiving())
		{
			try{
				clientSocket = getServer()->getSocket()->doAccept();
				//int sessionID = getServer()->getNewSessionID();
				SessionHandler* session = new SessionHandler(clientSocket, getServer());
				getServer()->getSessionsLst()->push_back(session);
				Log::getInstance()->info("[SERVER] Client accepted >> Socket: " + Log::getInstance()->intToString(clientSocket->getSocketConnection()));
				Thread* sessionThread = ThreadPool::getInstance()->execute(session);
				getServer()->getThreadsLst()->push_back(sessionThread);
			}
			catch (NetworkException& ne)
			{
				Log::getInstance()->error("[SERVER] startReceiving() ; Unexpected NetworkException..");
			}
		}
		//getServer()->getSocket()->doClose();
	}
	catch (exception& e)
	{
		string error = e.what();
		Log::getInstance()->error("[SERVER] startReceiving() ; Unexpected Running Error!! >> " + error);
	}
	return 0;
}
//------------------------------------------------------------------------------
void ServerReceiver::stopReceiving(void)
{
	setIsReceiving(false);
}